package com.happe.foodeasy.manage.controller;

import com.happe.foodeasy.manage.dto.ManagerLoginDTO;
import com.happe.foodeasy.manage.common.entity.ManagerEntity;
import com.happe.foodeasy.manage.service.ManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * This class is used to response the request of login in for manager.
 * Created by wubin on 2016-06-20.
 */
@Controller
@RequestMapping("/manage")
public class ManagerLoginOnController {
    private Logger logger = LoggerFactory.getLogger(ManagerLoginOnController.class);
    public static final String LOGIN_MANAGER_FLAG = "currentManager";

    private static final int USERNAME_PASSWORD_COOKIE_MAX_AGE = 60 * 60 * 24 * 10;
    private static final String USERNAME_PASSWORD_PATH = "/";

    @Autowired
    private ManagerService managerService;

    @RequestMapping("/loginOn.do")
    public
    @ResponseBody
    String loginOn(ManagerLoginDTO managerDTO, HttpServletRequest request, HttpServletResponse response) {
        ManagerEntity resultManager = managerService.checkManagerExist(managerDTO);
        String targetUrl;
        if (resultManager != null) {
            request.getSession().setAttribute(LOGIN_MANAGER_FLAG, resultManager);
            if (managerDTO.getRememberMe() != null) {
                createUsernameAndPassCookies(resultManager, response);
            }
            HttpSession session = request.getSession();
            targetUrl = (String) session.getAttribute("requestTarget");
            if (targetUrl != null) {
                session.removeAttribute("requestTarget");
            }
            logger.info(String.format("{\"success\":\"%s\"}", targetUrl != null ? targetUrl : "1"));
            return String.format("{\"success\":\"%s\"}", targetUrl != null ? targetUrl : "1");
        }

        return "0";
    }

    private void createUsernameAndPassCookies(ManagerEntity resultManager, HttpServletResponse response) {
        Cookie usernameCookie = new Cookie("username", resultManager.getUsername());
        usernameCookie.setMaxAge(USERNAME_PASSWORD_COOKIE_MAX_AGE);
        usernameCookie.setPath(USERNAME_PASSWORD_PATH);

        Cookie passwordCookie = new Cookie("password", resultManager.getPassword());
        passwordCookie.setMaxAge(USERNAME_PASSWORD_COOKIE_MAX_AGE);
        passwordCookie.setPath(USERNAME_PASSWORD_PATH);

        response.addCookie(usernameCookie);
        response.addCookie(passwordCookie);
    }
}
